package com.cms.manage.aspect;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.log4j.Logger;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;

import com.cms.manage.common.ConmonConfig;
import com.cms.manage.util.RequestMapToUtil;

@Aspect  
@Component 
public class PassVerifyAspect {

	private static Logger logger = Logger.getLogger(PassVerifyAspect.class);

	
	@Around("within(com.cms.manage.controller.*.*) && @annotation(passVerify)")
	public Object DataVerify(ProceedingJoinPoint joinPoint, PassVerify passVerify) {
	    String key = ConmonConfig.getKey();
		Map<String,Object> ERROR = new HashMap<String, Object>();
		ERROR.put("status", 0);
		ERROR.put("data", null);
		try {
			Object[] args = joinPoint.getArgs();
			HttpServletRequest request = null;
			for (int i = 0; i < args.length; i++) {
				if (args[i] instanceof HttpServletRequest) {
					request = (HttpServletRequest) args[i];
					break;
				}
			}
			if (request == null) {
				ERROR.put("message", "方法中缺失HttpServletRequest参数！");
				return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(ERROR);
			}
			Map<String,String> data =RequestMapToUtil.getPostByTextPlain(request);
			try {
				if(data.get("pass_key")==null||"".equals(data.get("pass_key"))){
					ERROR.put("message", "verify is null!");
					return ResponseEntity.status(HttpStatus.OK).body(ERROR);
				}
				if(data.get("user_id")==null||"".equals(data.get("user_id"))
						||data.get("user_name")==null||"".equals(data.get("user_name"))){
					ERROR.put("message", "param error(userid,username)!");
					return ResponseEntity.status(HttpStatus.OK).body(ERROR);
				}
			   String verify = DigestUtils.md5Hex(data.get("user_id")+data.get("user_name")+key);
			   verify =verify.substring(9,21);
				if(!verify.equals(data.get("pass_key"))){
					ERROR.put("message", "verify error!");
					return ResponseEntity.status(HttpStatus.OK).body(ERROR);
				}			
				return joinPoint.proceed();
			} catch (Exception e) {			
				ERROR.put("message", "系统异常" + e.getMessage());
				return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(ERROR);
			}
		} catch (Throwable e) {
			ERROR.put("message", "系统异常");
			return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(ERROR);
		}
	}


}
